import React from 'react';
import { Form, Input, Button, Alert, message, Col, Row } from 'antd';
import {
    AlipayCircleOutlined,
    TaobaoCircleOutlined,
    UserOutlined,
    WeiboCircleOutlined,
    LockOutlined,
    PhoneOutlined,
    SafetyOutlined
} from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { SelectLang, useIntl, Helmet, history } from '@umijs/max';
import { register, getCode } from '@/services/user';
import Settings from '../../../../config/defaultSettings';
import "./index.css";


// Action Icons Component
const ActionIcons = () => {
    const langClassName = useEmotionCss(({ token }) => ({
        marginLeft: '8px',
        color: 'rgba(0, 0, 0, 0.2)',
        fontSize: '24px',
        verticalAlign: 'middle',
        cursor: 'pointer',
        transition: 'color 0.3s',
        '&:hover': {
            color: token.colorPrimaryActive,
        },
    }));

    return (
        <>
            <AlipayCircleOutlined key="AlipayCircleOutlined" className={langClassName} />
            <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={langClassName} />
            <WeiboCircleOutlined key="WeiboCircleOutlined" className={langClassName} />
        </>
    );
};

// Language Selection Component
const Lang = () => {
    const langClassName = useEmotionCss(({ token }) => ({
        width: 42,
        height: 42,
        lineHeight: '42px',
        position: 'fixed',
        right: 16,
        borderRadius: token.borderRadius,
        ':hover': {
            backgroundColor: token.colorBgTextHover,
        },
    }));

    return (
        <div className={langClassName} data-lang>
            {SelectLang && <SelectLang />}
        </div>
    );
};

// Login Message Component
const LoginMessage: React.FC<{ content: string }> = ({ content }) => (
    <Alert
        style={{ marginBottom: 24 }}
        message={content}
        type="error"
        showIcon
    />
);

// Main Login Component
const Login: React.FC = () => {
    const [form] = Form.useForm();
    const intl = useIntl();

    // Send Code Function
    const sendCode = async () => {
        try {
            const phone = form.getFieldValue('phone');
            if (phone) {
                const res = await getCode(phone);
                if (res.status === 200) {
                    message.success("验证码发送成功");
                } else {
                    message.success("验证码发送成功");
                }
            } else {
                message.error("请先输入手机号");
            }
        } catch (error) {
            message.error("发送验证码时发生错误");
        }
    };

    // Handle Form Submit
    const handleSubmit = async (values: USERAPI.registerParams) => {
        try {

            const response = await register(values);

            if (response.status === 200) {
                window.localStorage.setItem("Authorization", response.token);
                window.localStorage.setItem("userInfo", JSON.stringify(response.data));
                message.success(intl.formatMessage({ id: 'pages.register.success', defaultMessage: '注册成功！' }));
                history.push('/user/login');
            } else {
                message.success(intl.formatMessage({ id: 'pages.register.success', defaultMessage: '注册成功！' }));
            }
        } catch (error) {
            console.error('注册错误:', error);

            message.error(intl.formatMessage({ id: 'pages.register.failure', defaultMessage: '注册失败，请重试！' }));
        } finally {
            history.push('/user/login');
        }
    };

    const containerClassName = useEmotionCss(() => ({
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage: "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        backgroundSize: '100% 100%',
    }));

    return (
        <div className={containerClassName}>
            <Button
                style={{ height: '32px', width: '64px', margin: '10px' }}
                onClick={() => window.location.href = '/landing'}
                type="primary"
                className="out-button"
            >
                返回
            </Button>
            <Helmet>
                <title>
                    {intl.formatMessage({ id: 'menu.register', defaultMessage: '注册页' })}
                    - {Settings.title}
                </title>
            </Helmet>
            <Lang />
            <div
                style={{
                    display: 'flex',
                    padding: '220px 0',
                    alignItems: 'center',
                    justifyContent: "center"
                }}
            >
                <Form
                    form={form}
                    name="register_form"
                    className="register-form"
                    onFinish={handleSubmit}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '用户名不能为空' }]}
                    >
                        <Input
                            prefix={<UserOutlined className="site-form-item-icon" />}
                            placeholder="请输入用户名"
                        />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '密码不能为空' }]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            placeholder="请输入密码"
                        />
                    </Form.Item>
                    <Form.Item
                        name="phone"
                        rules={[{ required: true, message: '手机号不能为空' }]}
                    >
                        <Row justify="start">
                            <Col span={16}>
                                <Input
                                    prefix={<PhoneOutlined className="site-form-item-icon" />}
                                    placeholder="请输入手机号"
                                />

                            </Col>
                            <Col span={7} style={{ transform: 'translateY(-10px)', marginLeft: '4px' }}>
                                <Button type="primary" block onClick={sendCode}>
                                    获取验证码
                                </Button>
                            </Col>
                        </Row>


                    </Form.Item>

                    <Form.Item
                        name="code"
                        rules={[{ required: true, message: '验证码不能为空' }]}
                    >
                        <Input
                            prefix={<SafetyOutlined className="site-form-item-icon" />}
                            placeholder="请输入验证码"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="login-form-button">
                            注册
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Login;
